package io.renren.modules.file.controller;

import com.google.common.collect.Lists;
import io.renren.common.utils.ResponseModel;
import io.renren.modules.file.entity.*;
import io.renren.modules.file.exception.FileException;
import io.renren.modules.file.service.FileService;
import io.renren.modules.file.service.FileUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("file")
@Api(tags = "文件上传下载")
public class FileController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Value("${server.servlet.context-path}")
    private String contentPath;

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private FileService fileService;


    @PostMapping("/uploadOss")
    @ApiOperation("单个上传文件->云服务器")
    public ResponseModel<UploadFileResponse> uploadOss(@RequestParam("file") MultipartFile file, @RequestParam("xtlx") String xtlx) throws IOException {
        FileEntity fileEntity = fileUploadService.storeOssFile(file, xtlx);
        UploadFileResponse fileResponse = new UploadFileResponse(fileEntity.getId(), fileEntity.getFileName(), fileEntity.getOriFileName(), fileEntity.getUrl(),
                fileEntity.getFileType(), fileEntity.getSuffix(), fileEntity.getUrl(), fileEntity.getSize());
        return ResponseModel.of(fileResponse);
    }


    @PostMapping("/uploadFile")
    @ApiOperation("单个上传文件")
    public ResponseModel<UploadFileResponse> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("xtlx") String xtlx){
        FileEntity fileEntity = fileUploadService.storeFile(file, xtlx);

        String downPath = "/file/downloadFile/" + String.valueOf(fileEntity.getId());

        UploadFileResponse fileResponse = new UploadFileResponse(fileEntity.getId(), fileEntity.getFileName(), fileEntity.getOriFileName(), downPath,
                fileEntity.getFileType(), fileEntity.getSuffix(), fileEntity.getUrl(), fileEntity.getSize());
        return ResponseModel.of(fileResponse);
    }

    @PostMapping("/uploadMultipleFiles")
    @ApiOperation("批量上传文件")
    public ResponseModel<List<UploadFileResponse>> uploadMultipleFiles(@RequestParam("files") MultipartFile[] files, @RequestParam("xtlx") String xtlx) {
        List<UploadFileResponse> list = Lists.newArrayList();

        if (files != null && files.length > 0) {
            for (int i = 0, len = files.length; i < len; i++) {
                FileEntity fileEntity = fileUploadService.storeFile(files[i], xtlx);
                String downPath = "/file/downloadFile/" + String.valueOf(fileEntity.getId());

                UploadFileResponse fileResponse = new UploadFileResponse(fileEntity.getId(), fileEntity.getFileName(), fileEntity.getOriFileName(), downPath,
                        fileEntity.getFileType(), fileEntity.getSuffix(), fileEntity.getUrl(), fileEntity.getSize());
                list.add(fileResponse);
            }
        }
        return ResponseModel.of(list);
    }

    @PostMapping("/uploadWangEditorFile")
    @ApiOperation("WangEditorFile-图片上传")
    public WangEditorResponse uploadWangEditorFile(@RequestParam("file") MultipartFile file){
        FileEntity fileEntity = fileUploadService.storeFile(file, "wangEditor");

        String downPath = ServletUriComponentsBuilder.fromCurrentContextPath().path("/file/downloadFile/" + String.valueOf(fileEntity.getId())).toUriString();

        WangEditorVo wangEditorVo = new WangEditorVo(downPath);
        WangEditorResponse wangEditorResponse = new WangEditorResponse();
        wangEditorResponse.setOne(wangEditorVo);

        return wangEditorResponse;
    }

    @GetMapping("/downloadFile/{id}")
    @ApiOperation("文件下载")
    public ResponseEntity<Resource> downloadFile(@PathVariable Integer id, HttpServletRequest request) {

        FileEntity fileEntity = fileService.getById(id);
        Resource resource = fileUploadService.loadFileAsResource(fileEntity);


        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if(contentType == null) {
            contentType = "application/octet-stream";
        }

        String fileName = fileEntity.getOriFileName();
        try {
            fileName = new String(fileName.getBytes("utf-8"),"ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .body(resource);
    }

    @PostMapping("/updateRelate")
    @ApiOperation("文件关联更新")
    public ResponseModel updateRelate(@RequestBody FileRelate fileRelate) {
        fileService.updateRelate(fileRelate);
        return ResponseModel.ok();
    }

}
